import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入配置路由规则
import routes from './router'
// 导入store
import store from '../store'
Vue.use(VueRouter)

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

/**
 * 访问控制：登陆过才能访问哪些页面
*/
router.beforeEach((to, form, next) => {
  const { user } = store.state
  const loginConfig = { path: '/login', query: { redirectUrl: to.path } }
  if (to.path.startsWith('/user') && !user.token) {
    // 没有登录 => 不能访问 => 跳到登录
    next(loginConfig)
  } else {
    next()
  }
})

export default router
